package com.baizhi.sync3;

/**
 * 死锁
 * 解决死锁原则：避免一个线程在持有一个锁的同时去申请另一个锁(不要锁里面套锁)
 */
public class SyncDemo04 {
    private static Object chopsticks = new Object(); //筷子
    private static Object spoon = new Object(); //勺子

    public static void main(String[] args) {
       Thread np = new Thread(()->{
           try{
               System.out.println("北方人开始吃饭");
               System.out.println("北方人拿起了筷子.....");
               synchronized (chopsticks){
                   System.out.println("北方人使用筷子开始吃饭.....");
                   Thread.sleep(5000);
                   System.out.println("北方人吃完了饭");
               }
               System.out.println("北方人放下了筷子，去拿勺子");

               synchronized (spoon){
                   System.out.println("北方人拿起了勺子，准备喝汤");
                   Thread.sleep(5000);
               }
               System.out.println("北方人放下了勺子");

               System.out.println("北方人吃饭完毕");

           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });



       Thread sp = new Thread(()->{
           try{
               System.out.println("南方人开始吃饭");
               System.out.println("南方人去拿勺子...");
               synchronized (spoon){
                   System.out.println("南方人拿起勺子准备喝汤");
                   Thread.sleep(5000);
                   System.out.println("南方人喝汤完毕");

               }
               System.out.println("南方人放下了勺子，准备拿筷子");

               synchronized (chopsticks){
                   System.out.println("南方人拿起了筷子开始吃饭");
                   Thread.sleep(5000);
               }
               System.out.println("南方人放下了筷子，吃饭完毕");

           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });


       np.start();
       sp.start();
    }
}
